<template>
  <div class="user-profile">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">
        <el-icon>
          <User />
        </el-icon>
        个人中心
      </h1>
      <p class="page-description">管理您的个人信息和账户设置</p>
    </div>

    <div class="profile-container">
      <!-- 用户信息卡片 -->
      <el-card class="user-info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
            <el-button type="primary" size="small" @click="showEditDialog = true">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
          </div>
        </template>

        <div class="user-info">
          <div class="avatar-section">
            <el-avatar :src="userStore.user?.avatarUrl" :size="80">
              <el-icon>
                <User />
              </el-icon>
            </el-avatar>
          </div>

          <div class="info-section">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="用户名">
                {{ userStore.user?.username || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="昵称">
                {{ userStore.user?.nickname || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="邮箱">
                {{ userStore.user?.email || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="手机号">
                {{ userStore.user?.phone || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="登录方式">
                <el-tag type="primary">
                  普通登录
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="注册时间">
                {{ formatDate(userStore.user?.createdAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="最后登录">
                {{ formatDate(userStore.user?.lastLoginTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="账户状态">
                <el-tag :type="userStore.user?.status === 1 ? 'success' : 'danger'">
                  {{ userStore.user?.status === 1 ? '正常' : '禁用' }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </el-card>

      <!-- 统计信息 -->
      <el-card class="stats-card" shadow="hover">
        <template #header>
          <span>使用统计</span>
        </template>

        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-icon">
              <el-icon>
                <Document />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ userStats.totalTemplatesCreated || 0 }}</div>
              <div class="stat-label">创建模板</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon">
              <el-icon>
                <DocumentCopy />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ userStats.totalScriptsGenerated || 0 }}</div>
              <div class="stat-label">脚本生成</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon">
              <el-icon>
                <Box />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ userStats.totalSoftwareSelected || 0 }}</div>
              <div class="stat-label">软件选择</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon">
              <el-icon>
                <Calendar />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ userStats.totalLoginDays || 0 }}</div>
              <div class="stat-label">登录天数</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon">
              <el-icon>
                <TrendCharts />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ userStats.consecutiveLoginDays || 0 }}</div>
              <div class="stat-label">连续登录</div>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon">
              <el-icon>
                <Star />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ userStats.totalTemplatesUsed || 0 }}</div>
              <div class="stat-label">模板使用</div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 快捷操作 -->
      <el-card class="actions-card" shadow="hover">
        <template #header>
          <span>快捷操作</span>
        </template>

        <div class="action-buttons">
          <el-button type="primary" @click="$router.push('/templates')">
            <el-icon>
              <Document />
            </el-icon>
            我的模板
          </el-button>
          <el-button type="success" @click="goToCreateTemplate">
            <el-icon>
              <Plus />
            </el-icon>
            创建模板
          </el-button>
          <el-button type="info" @click="$router.push('/template-market')">
            <el-icon>
              <Shop />
            </el-icon>
            模板广场
          </el-button>
          <el-button type="warning" @click="showChangePasswordDialog = true">
            <el-icon>
              <Lock />
            </el-icon>
            修改密码
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 编辑个人信息表单 -->
    <EditProfileForm v-model="showEditDialog" @success="handleEditSuccess" />

    <!-- 修改密码表单 -->
    <ChangePasswordForm v-model="showChangePasswordDialog" @success="handlePasswordChangeSuccess" />
  </div>
</template>

<script setup>
import
{
  Box,
  Calendar,
  Document,
  DocumentCopy,
  Edit,
  Lock,
  Plus,
  Shop,
  Star,
  TrendCharts,
  User
} from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import ChangePasswordForm from '../components/auth/ChangePasswordForm.vue'
import EditProfileForm from '../components/profile/EditProfileForm.vue'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const showEditDialog = ref(false)
const showChangePasswordDialog = ref(false)
const showCreateTemplateDialog = ref(false)

// 用户统计数据
const userStats = reactive({
  totalTemplatesCreated: 0,
  totalScriptsGenerated: 0,
  totalSoftwareSelected: 0,
  totalTemplatesUsed: 0,
  totalLoginDays: 0,
  consecutiveLoginDays: 0,
  favoriteOs: '',
  favoriteCategory: ''
})

// 事件处理
const handleEditSuccess = () =>
{
  ElMessage.success('个人信息更新成功')
}

const handlePasswordChangeSuccess = () =>
{
  ElMessage.success('密码修改成功')
}

const goToCreateTemplate = () =>
{
  // 设置标记，让我的模板页面自动打开创建弹窗
  sessionStorage.setItem('autoOpenCreateDialog', 'true')

  // 跳转到我的模板页面
  router.push('/templates')
}

// 生命周期
onMounted(() =>
{
  loadUserStats()
})

// 方法
const loadUserStats = async () =>
{
  try
  {
    // 开源版本跳过统计API调用
    const isOpenSourceVersion = true // 开源版本标识
    if (isOpenSourceVersion)
    {
      console.log('开源版本：跳过用户统计API调用')
      // 设置默认统计数据
      Object.assign(userStats, {
        totalProjects: 0,
        totalTemplates: 0,
        totalDownloads: 0,
        totalFavorites: 0,
        joinDays: Math.floor((Date.now() - new Date(userStore.user?.createdAt || Date.now()).getTime()) / (1000 * 60 * 60 * 24)) || 0
      })
      return
    }

    const response = await axios.get('/user/statistics', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (response.data.code === 200)
    {
      Object.assign(userStats, response.data.data)
    } else
    {
      throw new Error(response.data.message || '获取统计数据失败')
    }
  } catch (error)
  {
    console.error('加载用户统计失败:', error)

    // 显示友好的错误提示
    if (error.response)
    {
      // 服务器返回了错误状态码
      const status = error.response.status
      const data = error.response.data
      console.error('服务器错误:', status, data)

      if (status === 401)
      {
        ElMessage.error('用户未认证，请重新登录')
        // 清除用户信息并跳转到登录页
        userStore.logout()
        router.push('/')
      } else if (status === 403)
      {
        ElMessage.error('权限不足，无法访问统计数据')
      } else if (status >= 500)
      {
        ElMessage.error('服务器内部错误，请稍后重试')
      } else
      {
        ElMessage.warning(data?.message || '获取统计数据失败，请稍后重试')
      }
    } else if (error.request)
    {
      // 请求发送了但没有收到响应
      console.error('网络错误:', error.request)
      ElMessage.warning('网络连接失败，请检查网络连接')
    } else
    {
      // 其他错误
      console.error('未知错误:', error.message)
      ElMessage.warning('获取统计数据失败: ' + error.message)
    }

    // 使用默认值
    Object.assign(userStats, {
      totalTemplatesCreated: 0,
      totalScriptsGenerated: 0,
      totalSoftwareSelected: 0,
      totalTemplatesUsed: 0,
      totalLoginDays: 0,
      consecutiveLoginDays: 0
    })
  }
}



const formatDate = (dateString) =>
{
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}
</script>

<style scoped>
.user-profile {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.page-description {
  color: #7f8c8d;
  font-size: 16px;
}

.profile-container {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
}

.user-info-card {
  grid-row: span 2;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  gap: 24px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.info-section {
  flex: 1;
}

.stats-card {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: #e3f2fd;
  transform: translateY(-2px);
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff, #66b3ff);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
  flex-shrink: 0;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

.form-tip {
  margin-top: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.action-buttons {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.avatar-upload {
  text-align: center;
}

.avatar-uploader {
  display: inline-block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.upload-tips {
  margin-top: 12px;
  color: #7f8c8d;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    grid-template-columns: 1fr;
  }

  .user-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    grid-template-columns: 1fr;
  }
}
</style>
